<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-01-12 14:18:22
 * @Last Modified time: 2023-02-07 17:21:14
 */
namespace app\common\model\user;

use frank\base\BaseModel;
use frank\traits\ModelTrait;
use app\common\model\wechat\UserModel as WechatUserModel;
use app\common\model\user\UserGroupModel;
use app\common\model\store\OrderModel;
use app\common\enum\EnumFactory;

/**
 * 用户
 * Class  UserModel
 * @package app\common\model\user
 */
class UserModel extends BaseModel
{
    use ModelTrait;

    /**
     * 数据表主键
     */
    protected $pk = 'id';

    /**
     * 模型名称
     */
    protected $name = 'user';

    /**
     * 关联用户微信信息
     */
    public function wechat(){
        return $this->hasOne(WechatUserModel::class,'user_id','id')->bind([
            'wechat_openid'=>'wechat_openid',
            'wechat_openid'=>'weapp_openid',
            'wechat_unionid'=>'unionid',
        ]);
    }

    /**
     * 关联分组
     */
    public function group(){
        return $this->hasOne(UserGroupModel::class,'id','group_id')->bind([
            'group_name'=>'group_name',
        ]);
    }

    /**
     * 关联订单
     */
    public function order(){
        return $this->hasMany(OrderModel::class,'user_id','id');
    }

    /**
     * 状态修改器
     */
    public function getStatusAttr($value)
    {
        return EnumFactory::instance('user.status')->getItem($value);
    }

    /**
     * 注册来源修改器
     */
    public function getRegisterSourceAttr($value)
    {
        return EnumFactory::instance('user.register_source')->getItem($value);
    }

    /**
     * id搜索器
     */
    public function searchIdAttr($query, $value)
    {
        if (is_array($value)) {
            $query->whereIn('id', $value);
        } else {
            $query->where('id', $value);
        }
    }
}